package com.fengchao.api.service;

import com.fengchao.api.dao.trc.TrcAppOpenLogMapper;
import com.fengchao.api.dao.trc.TrcServerErrorLogMapper;
import com.fengchao.api.dao.usr.UsrAppChannelMapper;
import com.fengchao.api.dao.usr.UsrAppDeviceUserMapper;
import com.fengchao.model.trc.TrcAppOpenLog;
import com.fengchao.model.usr.UsrAppChannel;
import com.fengchao.model.usr.UsrAppDeviceUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * Created by wangnina 6/6.
 */
@Service
public class TrcService {
    @Autowired
    private TrcAppOpenLogMapper trcAppOpenLogMapper;
    @Autowired
    private UsrAppDeviceUserMapper usrAppDeviceUserMapper;
    @Autowired
    private UsrAppChannelMapper usrAppChannelMapper;
    @Autowired
    private TrcServerErrorLogMapper trcServerErrorLogMapper;


    @Transactional
    public boolean record(String token, Integer deviceId, Integer appVersion, String appChannelCode, String deviceIp, Boolean isFirstOpen) {
        UsrAppDeviceUser usrAppDeviceUser = usrAppDeviceUserMapper.findByAccessToken(token);
        UsrAppChannel usrAppChannel = usrAppChannelMapper.findByChannelCode(appChannelCode);
        TrcAppOpenLog trcAppOpenLog = new TrcAppOpenLog();
        trcAppOpenLog.setDeviceId(deviceId);
        trcAppOpenLog.setAppChannelCode(appChannelCode);
        trcAppOpenLog.setAppChannelName(usrAppChannel != null ? usrAppChannel.getChannelName() : null);
        trcAppOpenLog.setAppVersion(appVersion);
        trcAppOpenLog.setDeviceIp(deviceIp);
        trcAppOpenLog.setIsFirstOpen(isFirstOpen);
        trcAppOpenLog.setOpenTime(new Date());
        trcAppOpenLog.setUserId(usrAppDeviceUser != null ? usrAppDeviceUser.getUserId() : null);
        Integer count = trcAppOpenLogMapper.insertSelective(trcAppOpenLog);
        if (count > 0) {
            return true;
        } else {
            return false;
        }
    }

    @Transactional
    public Integer recordErrorLog(String addressUrl, String parameter, String ip, String type, String info) {
        return trcServerErrorLogMapper.insertErrorLog(null, addressUrl, parameter, ip, type, info);
    }

}
